<?php
/**
 * AtLeastValidator
 *
 * @author   Vladimir Galajda <galajda@gmail.com>
 **/
class AtLeastValidator extends CValidator /*implements CListIterator*/ 
{
    /**
     * @param CModel $object
     * @param array $attributes
     */
   // public function validate(CModel $object, $attributes)
   public function validate($object,$attributes=null)
    {
        parent::validate($object, $attributes);
        $object->onAfterValidate = array($this, 'afterValidate');
    }

    /**
     * @param CModel $object
     * @param string $attribute
     */
    public function validateAttribute($object, $attribute)
    {
		/*echo "<br />helloo<br />";
		print_r($this->attributes);
		echo "<br /><br />"; */
		//print_r($attribute); exit;
		
		
		 /* foreach ($this->attributes as $attribute) {    
			  if ($attribute !== NULL) {
					$object->addError($attribute, '');
				//break;
			  }
		 }*/	
    }

    public function afterValidate($event)
    { 
    	//$attributes = array('id'=>'Id','name'=>'Name','email'=>'Email');
    	//echo "<pre>AFTER VALIDATE";
        /** @var $sender CModel */
        $sender = $event->sender;
       // echo "<br />model";
		//print_r($sender->attributes);
        $valid = false;
		//echo "<br />Attribute";
		//print_r($this->attributes); 
		//echo "<br />Attribute->single";
		//print_r($attribute);
		//exit;
        foreach($this->attributes as $attribute) {
            if ($sender->$attribute != null) {
            	//echo "<br />".$attribute;
                $valid = true;
                break;
            }
        }

        if ($valid) 
        {
            foreach($this->attributes as $attribute) 
            {
                $sender->clearErrors($attribute);
            }
        }
        else 
        {
        	$arrNewArrayAttri = array();
        	$arrAttri = array();
        	if(isset($sender->scenario) && $sender->scenario == 'clientsearch')
        	{
        		$arrAttri = array('id'=>'Client Id','name'=>'Client Name','email'=>'Client Email');
        	}
        	elseif (isset($sender->scenario) && $sender->scenario == 'companysearch')
        	{
        		$arrAttri = array('id'=>'Company Id','name'=>'Company Name','email'=>'Company Email');
        	}
        	 
        	foreach($this->attributes as $attribute) 
            {
            	if(isset($attribute) &&  array_key_exists ($attribute, $arrAttri))
            	{
            		$arrNewArrayAttri[] =   $arrAttri[$attribute]  ;
            	}
            }
        	//echo $sender->scenario;
            $sender->addError(null, 'Fill at least one of the following attributes:   ' . "&nbsp;<tt><b>".ucwords(implode(', ', $arrNewArrayAttri))."</b></tt>");
        }
    }
}